import {Component, OnInit, Input, Output, EventEmitter, AfterViewInit, ViewChild} from '@angular/core';
import * as Handsontable from 'handsontable';
import {HotTableRegisterer} from '@handsontable/angular';

@Component({
  selector: 'app-hot-table',
  templateUrl: './hot-table.component.html',
  styleUrls: ['./hot-table.component.scss']
})
export class HotTableComponent implements OnInit, AfterViewInit {

  @Input()
  set option(option: any) {
    this._option = option;
    this.hotSettings = {...this.setting, ...option};
    if (this.hotTableIns) {
      this.hotTableIns.updateSettings(this.hotSettings);
    }
  }

  get option(): any {
    return this._option;
  }

  @Input() hotTableId = 'hotInstance';

  @Output() tableChanged = new EventEmitter<any>();
  @Output() tableClicked = new EventEmitter<any>();
  @Output() selectedRange = new EventEmitter<any>();
  // tslint:disable-next-line:variable-name
  _option;
  hotRegisterer = new HotTableRegisterer();
  hotTableIns;
  // tslint:disable-next-line:variable-name
  _cornerSettings = {
    showCorner: false,
    text: '时间',
    height: '50px',
    width: '50px',
    lineHeight: '50px',
    showContextMenu: true
  };
  @Input()
  set cornerSettings(data: any) {
    this._cornerSettings = {...this._cornerSettings, ...data};
  }

  get cornerSettings(): any {
    return this._cornerSettings;
  }

  setting = {
    data: [['暂无数据']],
    rowHeaders: false,             // 行头
    colHeaders: ['标题'],             // 列头
    className: 'htCenter htMiddle',
    stretchH: 'all',              // 表格主题铺满容器
    fillHandle: true,            // 右下角copy功能
    manualColumnResize: false,   // 可调整列宽
    manualRowResize: false,      // 可调整行高
    currentRowClassName: 'hot-table-current-row', // 当前选中行
    contextMenu: this.menuSetting(),            // 右键菜单
    afterChange: changes => {
      const obj = {
        changes: changes,
        data: this.hotSettings.data
      };
      this.tableChanged.emit(obj);
    },
    afterOnCellMouseDown: (event, coords, td) => {
      const data = {
        event: event,
        coords: coords,
        td: td
      };
      this.tableClicked.emit(data);
    },
    afterSelectionEnd: (row, column, row2, column2, selectionLayerLevel) => {
      this.selectedRange.emit(this.hotTableIns.getSelectedRange());
    }
  };
  // @ts-ignore
  hotSettings: Handsontable.GridSettings = {...this.setting, ...this._option};

  ngOnInit(): void {
    this.hotSettings.contextMenu = this.option.contextMenu ? this.menuSetting() : false;
  }

  ngAfterViewInit(): void {
    this.hotTableIns = this.hotRegisterer.getInstance(this.hotTableId);
  }

  update(): void {
    if (this.hotTableIns) {
      this.hotTableIns.render();
    }
  }

  menuSetting(): void {
    const that = this;
    // @ts-ignore
    const menuSettings: Handsontable.contextMenu.Settings = {
      // @ts-ignore
      callback(key: string, options: Handsontable.contextMenu.Options) {
        // Common callback for all options
        // console.log(key, options);
        const hotInstance = this.getInstance();
        const exportPlugin = hotInstance.getPlugin('exportFile');
        const handData = hotInstance.getData();
        const hotTable = [];   // 获取修改后的表格数据不包括多行头数据
        options = options[0];

        if (key === 'after') {
          const startIndex = [options.start.row, options.start.col];
          const endIndex = [options.end.row, options.end.col];

          // 单列向下的情况
          if (startIndex[1] === endIndex[1]) {
            const loopNum = endIndex[0] - startIndex[0];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];
            const nowVal = hotInstance.getDataAtCell(startIndex[0], startIndex[1]);
            for (let i = 0; i < loopNum; i++) {
              const nowRow = rowNum + i + 1;
              handData[nowRow].splice(columnNum, 1, nowVal);
            }
          } else {
            const loopNumCol = endIndex[1] - startIndex[1];
            const loopNumRow = endIndex[0] - startIndex[0];

            const nowValArr = [];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];

            for (let z = 0; z < loopNumCol + 1; z++) {
              const val = hotInstance.getDataAtCell(startIndex[0], startIndex[1] + z);
              nowValArr.push(val);
            }
            for (let j = columnNum; j <= endIndex[1]; j++) {
              for (let i = 0; i < loopNumRow; i++) {
                const val = nowValArr[j - columnNum];
                handData[rowNum + i + 1].splice(j, 1, val);
              }
            }
          }
        }
        if (key === 'before') {
          const startIndex = [options.start.row, options.start.col];
          const endIndex = [options.end.row, options.end.col];

          // 单列向上的情况
          if (startIndex[1] === endIndex[1]) {
            const loopNum = startIndex[0];
            const rowNum = endIndex[0];
            const columnNum = endIndex[1];
            const nowVal = hotInstance.getDataAtCell(endIndex[0], endIndex[1]);
            for (let i = rowNum; i > loopNum; i--) {
              const nowRow = rowNum + i + 1;
              handData[i - 1].splice(columnNum, 1, nowVal);
            }
          } else {
            const loopNumCol = endIndex[1] - startIndex[1];
            const loopNumRow = endIndex[0] - startIndex[0];
            const nowValArr = [];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];

            for (let z = 0; z < loopNumCol + 1; z++) {
              const val = hotInstance.getDataAtCell(endIndex[0], startIndex[1] + z);
              nowValArr.push(val);
            }
            for (let j = columnNum; j <= endIndex[1]; j++) {
              for (let i = 0; i < loopNumRow; i++) {
                const val = nowValArr[j - columnNum];
                handData[rowNum + i].splice(j, 1, val);
              }
            }
          }
        }
        if (key === 'rate') {
          // _self.setState({
          //   visible: true,
          //   selectOptions: options
          // });
        }
        if (key === 'beforeAfter') {
          const array = [options.start.row, options.start.col, options.end.row, options.end.col];
          if (array[0] === array[2]) {
            return false;
          }
          for (let i = array[1]; i <= array[3]; i++) {
            const k = (handData[array[2]][i] - handData[array[0]][i]) / (options.end.row - options.start.row);
            const scale = k.toFixed(4);
            const a = handData[array[0]][i] - array[0] * Number(scale);

            for (let n = array[0]; n <= array[2]; n++) {
              handData[n][i] = n * k + a + '';
            }
          }
        }
        if (key === 'left') {
          const startIndex = [options.start.row, options.start.col];
          const endIndex = [options.end.row, options.end.col];
          // 单行向左的情况
          if (startIndex[0] === endIndex[0]) {
            const loopNum = endIndex[1] - startIndex[1];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];
            const nowVal = hotInstance.getDataAtCell(endIndex[0], endIndex[1]);
            for (let i = 0; i < loopNum; i++) {
              const nowCol = columnNum + i;
              handData[rowNum].splice(nowCol, 1, nowVal);
            }
          } else {
            const loopNumCol = endIndex[1] - startIndex[1];
            const loopNumRow = endIndex[0] - startIndex[0];

            const nowValArr = [];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];

            for (let z = 0; z < loopNumRow + 1; z++) {
              const val = hotInstance.getDataAtCell(startIndex[0] + z, endIndex[1]);
              nowValArr.push(val);
            }
            for (let j = rowNum; j <= endIndex[0]; j++) {
              for (let i = 0; i < loopNumCol; i++) {
                const val = nowValArr[j - rowNum];
                handData[j].splice(columnNum + i, 1, val);
              }
            }
          }
        }
        if (key === 'right') {
          const startIndex = [options.start.row, options.start.col];
          const endIndex = [options.end.row, options.end.col];
          // 单行向右的情况
          if (startIndex[0] === endIndex[0]) {
            const loopNum = endIndex[1] - startIndex[1];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];
            const nowVal = hotInstance.getDataAtCell(startIndex[0], startIndex[1]);
            for (let i = 0; i < loopNum; i++) {
              const nowCol = columnNum + i + 1;
              handData[rowNum].splice(nowCol, 1, nowVal);
            }
          } else {
            const loopNumCol = endIndex[1] - startIndex[1];
            const loopNumRow = endIndex[0] - startIndex[0];

            const nowValArr = [];
            const rowNum = startIndex[0];
            const columnNum = startIndex[1];

            for (let z = 0; z < loopNumRow + 1; z++) {
              const val = hotInstance.getDataAtCell(startIndex[0] + z, startIndex[1]);
              nowValArr.push(val);
            }
            for (let j = rowNum; j <= endIndex[0]; j++) {
              for (let i = 0; i < loopNumCol; i++) {
                const val = nowValArr[j - rowNum];
                handData[j].splice(columnNum + i + 1, 1, val);
              }
            }
          }
        }

        if (key === 'exportFile') {
          exportPlugin.downloadFile('csv', {
            filename: 'MyFile',
            exportHiddenRows: false,     // default false
            exportHiddenColumns: false,  // default false
            columnHeaders: true,        // default false
            rowHeaders: false           // default false
          });
        }

        if (hotTable.length > 0) {
          // _self.state.settings.data = hotTable;
        } else {
          hotInstance.loadData(handData);
        }

        // _self.setState({
        //   settings: _self.state.settings
        // });
      },
      items: {
        after: {name: '向后填充'},
        // "left": { name: '向左填充' },
        hsep1: '---------',
        before: {name: '向前填充'},
        // "right": { name: '向右填充' },
        // hsep2: '---------',
        // rate: {name: '倍率缩放'},
        hsep3: '---------',
        beforeAfter: {name: '前后内插'},
        // hsep4: '---------',
        // row_below: {name: '插入一行'},
        hsep5: '---------',
        exportFile: {name: '导出表格'}
      }
    };
    return menuSettings;

  }

}
